//
//  WFCUProfileTableViewController.m
//  WFChat UIKit
//
//  Created by WF Chat on 2017/10/22.
//  Copyright © 2017年 WildFireChat. All rights reserved.
//

#import "WFCUMyProfileTableViewController.h"
#import <SDWebImage/SDWebImage.h>
#import <WFChatClient/WFCChatClient.h>
#import "WFCUMessageListViewController.h"
#import "MBProgressHUD.h"

#import "WFCUModifyMyProfileViewController.h"
#import "QrCodeHelper.h"
#import "WFCUConfigManager.h"
#import "WFCUImage.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "LBXScanNative.h"

#import <Photos/Photos.h>


@interface WFCUMyProfileTableViewController () <UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic)UIImageView *portraitView;
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray<UITableViewCell *> *cells1;
@property (nonatomic, strong)NSMutableArray<UITableViewCell *> *cells2;
@property (nonatomic, strong)WFCCUserInfo *userInfo;
@property (nonatomic, strong)UIView * inputView ;
//@property (nonatomic, strong) UIImageView* qrImgView;
@property (nonatomic, strong)UILabel *titleL;
@end

@implementation WFCUMyProfileTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.tableHeaderView = nil;

    self.tableView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoUpdated:) name:kUserInfoUpdated object:nil];
    
    self.title = WFCString(@"MyInformation");
    
//    self.navigationItem.backBarButtonItem.title = @"" ;
//    self.navigationItem.backBarButtonItem.title = @"" ;
//    self.navigationItem.backButtonTitle = @"" ;
//    
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
//    item.title = @"" ;
//    self.navigationItem.backBarButtonItem = item;
    
   
}

- (void)onUserInfoUpdated:(NSNotification *)notification {
    NSArray<WFCCUserInfo *> *userInfoList = notification.userInfo[@"userInfoList"];
    for (WFCCUserInfo *userInfo in userInfoList) {
        if ([[WFCCNetworkService sharedInstance].userId isEqualToString:userInfo.userId]) {
            [self loadData:NO];
            break;
        }
    }
}

- (NSString *)getGenderString:(int)gender {
    if (gender == 0) {
        return @"";
    } else if(gender == 1) {
        return WFCString(@"Male");
    } else if(gender == 2) {
        return WFCString(@"Female");
    }
    
    return WFCString(@"Other");
}

- (void)loadData:(BOOL)refresh {
    self.cells1 = [[NSMutableArray alloc] init];
    self.cells2 = [[NSMutableArray alloc] init];
    self.userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:refresh];
    
    UITableViewCell *headerCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    for (UIView *subView in headerCell.subviews) {
        [subView removeFromSuperview];
    }
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    WEAKSELF_ZM
    self.portraitView = [[UIImageView alloc] initWithFrame:CGRectMake(12, 8 + 5, 54, 54)];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onViewPortrait:)];
//    [self.portraitView addGestureRecognizer:tap];
    self.portraitView.userInteractionEnabled = YES;
    self.portraitView.layer.cornerRadius = 10;
    self.portraitView.layer.masksToBounds = YES;
    [self.portraitView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [weakSelf onViewPortrait:gestureRecoginzer.view];
    }];
    [self.portraitView sd_setImageWithURL:[NSURL URLWithString:[self.userInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"]];
    
    [headerCell.contentView addSubview:self.portraitView];
    
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(80 + 5, 20, width - 108 - 28, 20)];
    [title setFont:[UIFont systemFontOfSize:16]];
    [title setText:self.userInfo.displayName];
    [headerCell addSubview:title];

    self.titleL = title;
    UILabel *Account = [[UILabel alloc] initWithFrame:CGRectMake(80 + 5, 20 + 20 + 4, width - 108 - 28, 20)];
    [Account setFont:[UIFont systemFontOfSize:12]];
    Account.textColor = [UIColor colorWithHexExtendString:@"#8D8B9B"];
//    [Account setText:[NSString stringWithFormat:@"TL畅聊ID:%@",self.userInfo.name]];
    
    Account.textColor = [UIColor colorWithHexExtendString:@"#8D8B9B"];
    
    
    NSString *str = [NSString stringWithFormat:@"TL畅聊ID:%@", self.userInfo.name];
    if (self.userInfo.extra.length > 1) {
        
        NSDictionary *dic =  [self.userInfo.extra jk_JSONStringWithDictionary];
 
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str attributes:@{}];
        [att addAttribute:NSForegroundColorAttributeName value:[[dic handleNullObjectForKey:@"isVip"] intValue] == 1 ? [UIColor colorWithHexExtendString:@"#FFA332"] : [UIColor colorWithHexExtendString:@"#8D8B9B"] range:NSMakeRange(str.length - self.userInfo.name.length ,   self.userInfo.name.length )];

        Account.attributedText = att ; ///[NSString stringWithFormat:@"TL畅聊号:%@", self.userInfo.name];
        ///
    } else {
        Account.text = str;
    }
    
    
    [headerCell addSubview:Account];
    
    
    
    headerCell.tag = -1;
    headerCell.accessoryType = UITableViewCellAccessoryNone;
    [self addLabel:WFCString(@"") onCell:headerCell isHeaderCell:YES isLeft:YES];
    [self.cells1 addObject:headerCell];

    UIButton *set = [[UIButton alloc] init];
    [headerCell.contentView addSubview:set];
    headerCell.userInteractionEnabled = YES;
    set.sh_chain_extend.image_loc(@"me_edit").addTarget_action(self, @selector(setupName));
    set.sd_layout.centerYEqualToView(headerCell.contentView).rightSpaceToView(headerCell.contentView, 5).widthIs(50).heightIs(24);
    
    
    UITableViewCell *cell = [self getAttrCell:WFCString(@"设置昵称或别名") rightText:@"" mutable:YES];
//    cell.tag = Modify_DisplayName;
//    [self.cells1 addObject:cell];
    
    
    
    
    
 

//    cell = [self getAttrCell:WFCString(@"Account") rightText:self.userInfo.name mutable:YES];
//    cell.tag = 100;
//    [self.cells1 addObject:cell];

//    cell = [self getAttrCell:WFCString(@"Mobile") rightText:self.userInfo.mobile mutable:YES];
//    cell.tag = Modify_Mobile;
//    [self.cells2 addObject:cell];

    cell = [self getAttrCell:WFCString(@"QRCode") rightText:@"" mutable:YES];
    cell.tag = 1000;
    [self.cells2 addObject:cell];
    UIImage *qrcode = [WFCUImage imageNamed:@"qrcode"];
    
    UIImageView *qrview = [[UIImageView alloc] initWithFrame:CGRectMake(15, 17, 20, 20)];
    qrview.image = qrcode;
    [cell addSubview:qrview];
    
    UILabel *lab = [cell viewWithTag:1];
    if (lab) {
        lab.sd_layout.leftSpaceToView(cell, 50).centerYEqualToView(cell).autoHeightRatio(0);
        [lab setSingleLineAutoResizeWithMaxWidth:100];
    }
    
    
//    cell = [self getAttrCell:WFCString(@"Gender") rightText: [self getGenderString:self.userInfo.gender] mutable:YES];
//    cell.tag = Modify_Gender;
//    [self.cells2 addObject:cell];
//
//    cell = [self getAttrCell:WFCString(@"Email") rightText:self.userInfo.email mutable:YES];
//    cell.tag = Modify_Email;
//    [self.cells2 addObject:cell];
//
//    cell = [self getAttrCell:WFCString(@"Address") rightText:self.userInfo.address mutable:YES];
//    cell.tag = Modify_Address;
//    [self.cells2 addObject:cell];
//
//    cell = [self getAttrCell:WFCString(@"Company") rightText:self.userInfo.company mutable:YES];
//    cell.tag = Modify_Company;
//    [self.cells2 addObject:cell];
//
//    cell = [self getAttrCell:WFCString(@"SocialAccount") rightText:self.userInfo.social mutable:YES];
//    cell.tag = Modify_Social;
//    [self.cells2 addObject:cell];
    
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData:YES];
}

- (UITableViewCell *)getAttrCell:(NSString *)leftText rightText:(NSString *)rightText mutable:(BOOL)mutable {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
//    for (UIView *subView in cell.subviews) {
//        [subView removeFromSuperview];
//    }
    if (!mutable) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else {

        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];

    }

    cell.tag = -1;
    [self addLabel:leftText onCell:cell isHeaderCell:NO isLeft:YES];
//    if (rightText.length == 0) {
//        rightText = @"未填写";
//    }
    [self addLabel:rightText onCell:cell isHeaderCell:NO isLeft:NO];
    return cell;
}

- (void)addLabel:(NSString *)titleStr onCell:(UITableViewCell *)cell isHeaderCell:(BOOL)isHeaderCell isLeft:(BOOL)left {
    UILabel *title ;
    if (isHeaderCell) {
        title = [[UILabel alloc] initWithFrame:CGRectMake(8, 4, 68, 68)];
    } else {
        if (left) {
            title = [[UILabel alloc] initWithFrame:CGRectMake(8, 7, 133, 36)];
        } else {
            CGFloat width = [UIScreen mainScreen].bounds.size.width;
            title = [[UILabel alloc] initWithFrame:CGRectMake(88, 7, width - 108 - 28, 36)];
        }
    }
    
    [title setFont:[UIFont systemFontOfSize:16]];
    [title setText:titleStr];
    if (left) {
        [title setTextAlignment:NSTextAlignmentLeft];
        title.tag = 1;
    } else {
        [title setTextAlignment:NSTextAlignmentRight];
        title.tag = 2;
    }
    
    [cell addSubview:title];
}

- (void)onViewPortrait:(id)sender {
    WFCUMyPortraitViewController *pvc = [[WFCUMyPortraitViewController alloc] init];
    pvc.userId = self.userInfo.userId;
//    [self.navigationController pushViewController:pvc animated:YES];
    pvc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:pvc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UITableViewDataSource<NSObject>
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.cells1.count;
    }
    return self.cells2.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.cells1[indexPath.row];
    }
    return self.cells2[indexPath.row];
}

- (void)showMyQrCode {
    if (gQrCodeDelegate) {
        [gQrCodeDelegate showQrCodeViewController:self.navigationController type:QRType_User target:[WFCCNetworkService sharedInstance].userId];
    }
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 && indexPath.section == 0) {
//        WFCUMyPortraitViewController *pvc = [[WFCUMyPortraitViewController alloc] init];
//        pvc.userId = [WFCCNetworkService sharedInstance].userId;
//        [self.navigationController pushViewController:pvc animated:YES];
    } else {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell.tag == 1000) {
//            [self showMyQrCode];
            
            
            [([UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject) addSubview:self.inputView];
            self.inputView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));

            return;
        }
        if (cell.tag < 0) {
            return;
        }
        
        if (cell.tag == Modify_Gender) {
            [self sexAlterView];
            return;
        }
        
        WFCUModifyMyProfileViewController *mpvc = [[WFCUModifyMyProfileViewController alloc] init];
        mpvc.modifyType = cell.tag;
        __weak typeof(self)ws = self;
        mpvc.onModified = ^(NSInteger modifyType, NSString *value) {
            NSArray *cells =ws.cells2;
            if (indexPath.section == 0) {
                cells = ws.cells1;
            }
            for (UITableViewCell *cell in cells) {
                if (cell.tag == modifyType) {
                    for (UIView *view in cell.subviews) {
                        if (view.tag == 2) {
                            UILabel *label = (UILabel *)view;
                            label.text = value;
                        }
                    }
                }
            }
        };
        [self.navigationController pushViewController:mpvc animated:YES];
    }
}
- (void)setupName{
    
    WFCUModifyMyProfileViewController *mpvc = [[WFCUModifyMyProfileViewController alloc] init];
    mpvc.modifyType = 0;
    __weak typeof(self)ws = self;
    mpvc.onModified = ^(NSInteger modifyType, NSString *value) {
        
        
        ws.titleL.text = value;

    };
    [self.navigationController pushViewController:mpvc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 80;
    } else {
        return 55 ;
    }
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return @" ";
//}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    } else {
         
    }
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [WFCUConfigManager globalManager].backgroudColor ;
    return view;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.backgroundColor = [UIColor clearColor] ;
}
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.backgroundColor = [UIColor clearColor] ;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 10.f;
    }
}
- (void)updateGender:(int)gender {
    __weak typeof(self) ws = self;
    
    __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = WFCString(@"Updating");
    [hud showAnimated:YES];
    
    [[WFCCIMService sharedWFCIMService] modifyMyInfo:@{@(Modify_Gender):[NSString stringWithFormat:@"%d", gender]} success:^{
        [hud hideAnimated:NO];
        for (UITableViewCell *cell in ws.cells2) {
            if (cell.tag == Modify_Gender) {
                for (UIView *v in cell.subviews) {
                    if ([v isKindOfClass:[UILabel class]] && v.tag == 2) {
                        UILabel *label = (UILabel *)v;
                        label.text = [ws getGenderString:gender];
                        break;
                    }
                }
                break;
            }
        }
    } error:^(int error_code) {
        [hud hideAnimated:NO];
        
        hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = WFCString(@"UpdateFailure");
        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
        [hud hideAnimated:YES afterDelay:1.f];
    }];
}

- (void)sexAlterView{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:WFCString(@"Male") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self updateGender:1];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:WFCString(@"Female") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self updateGender:2];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:WFCString(@"Other") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self updateGender:3];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [[UIView alloc]init];
        
        _inputView.sh_chain_extend.backgroundColor([UIColor colorWithHexExtendString:@"#3F3C41" alpha:0.57]).addTarget_action(self, @selector(removeMain));

        UIView *view = [[UIView alloc]init];
        [_inputView addSubview:view];
        view.sd_layout.centerXEqualToView(self.inputView).centerYEqualToView(self.inputView).offset(-25) .widthIs(128 + 50) ;
        view.sh_chain_extend.backgroundColorWhite().roundSize(15);

 
      
        UIView *viewC = [[UIView alloc]init];
        [view addSubview:viewC];
        viewC.sd_layout.centerXEqualToView(view).topSpaceToView(view, 25).heightIs(128).widthIs(128);
        viewC.sh_chain_extend.backgroundColorWhite();
        
        
        UIImageView *qrImgView = [[UIImageView alloc]init];
        [viewC addSubview:qrImgView];
        qrImgView.sd_layout.centerXEqualToView(viewC).centerYEqualToView(viewC).heightIs(128).widthIs(128);

        
        NSString *qrStr = [NSString stringWithFormat:@"wildfirechat://user/%@", [WFCCNetworkService sharedInstance].userId ];

        qrImgView.image = [LBXScanNative createQRWithString:qrStr QRSize:qrImgView.bounds.size];

         
        
        
        [view setupAutoHeightWithBottomView:viewC bottomMargin:25];
        
        UIButton *lab1 = [[UIButton alloc]init];
        
        [_inputView addSubview:lab1];
        lab1.sd_layout.topSpaceToView(view, 25).centerXEqualToView(_inputView).heightIs(30).widthIs(100);
 
        lab1.sh_chain_extend.title(@"二维码扫一扫").titleColorWhite().font_size_bold(14).modeFit() ;
        
        
        
        
        
        UIButton *save = [[UIButton alloc]init];
        
        [_inputView addSubview:save];
        save.sd_layout.topSpaceToView(lab1, 68).centerXEqualToView(_inputView).heightIs(40).widthIs(86);
 
        save.sh_chain_extend.title(@"保存图片").titleColorWhite().font_size_bold(14).roundSize(5).borderWidth(2).borderColor([UIColor whiteColor]);
        
        WEAKSELF_ZM
        [save jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
           
            

            
            // 判断授权状态
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status != PHAuthorizationStatusAuthorized) return;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSError *error = nil;
                    // 保存相片到相机胶卷
                    __block PHObjectPlaceholder *createdAsset = nil;
                    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                        PHAssetCreationRequest *creationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:[UIImage getImageFromView:viewC]];
                        creationRequest.creationDate = [NSDate date];
                        createdAsset = creationRequest.placeholderForCreatedAsset;
                    } error:&error];
                    
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.inputView animated:YES];
                    hud.mode = MBProgressHUDModeText;
                      
                    if (error) {
                        NSLog(@"保存失败");
                        hud.label.text = WFCString(@"保存失败");

                        
                        return;
                    }else {
                        NSLog(@"保存成功");
                        hud.label.text = WFCString(@"保存成功");

                    }
                    

                    [hud hideAnimated:YES afterDelay:1.f];
                 
                     
                });
            }];
            
            
            
        }];
        
        
        
        
        
        
        
    }
    return _inputView;
}





- (void)on1Register  {
   [self removeMain];
   

}
- (void)removeMain
{

    [UIView animateWithDuration:0.15 animations:^{

        self.inputView.alpha = 0 ;
    } completion:^(BOOL finished) {
        self.inputView.hidden = YES;
        [self.inputView removeFromSuperview];
        self.inputView  = nil;

    }];
    
}


@end
